import importlib
import os


class index:
    def __init__(self):
        self.apps = []
        '''
    以下对于小白来说照抄即可，大佬可尝试不同的加载apps方式
     '''

    def load_apps(self):

        # 加载plugin/example-plugins/apps文件夹中的模块
        module_names = []
        apps_dir = os.path.join(os.path.dirname(__file__), "apps")
        for file in os.listdir(apps_dir):
            if file.endswith(".py"):
                module_names.append(file[:-3])

        for module_name in module_names:
            module = importlib.import_module("plugins.example-plugin.apps." + module_name)  # 记得更改路径
            cls_name = "App" + module_name.capitalize()
            app_class = getattr(module, cls_name)
            app_instance = app_class()
            self.apps.append(app_instance)

    def priority(self):  # 照抄即可
        return 1

    def should_trigger(self, message, event):  # 照抄即可
        self.load_apps()
        for app in sorted(self.apps, key=lambda x: x.priority(), reverse=True):
            if app.should_trigger(message, event):
                return True
        return False

    async def execute(self, message, api, event):  # 照抄即可
        for app in sorted(self.apps, key=lambda x: x.priority(), reverse=True):
            if app.should_trigger(message, event):
                triggered = await app.execute(message, api, event)
                if triggered:
                    return True
        return False  # 一定要为False
